import os
import fitz

def pdf_first_page_to_png(source_dir, target_dir, zoom=3):
    """
    增强版PDF首页转换函数，带进度显示
    """
    # 预检PDF文件
    pdf_files = [f for f in os.listdir(source_dir) if f.lower().endswith('.pdf')]
    total = len(pdf_files)
    
    if not pdf_files:
        print("⚠️ 未找到PDF文件")
        return

    # 创建输出目录
    os.makedirs(target_dir, exist_ok=True)
    
    print(f"📁 发现 {total} 个PDF文件")
    print("🔄 开始转换...\n")

    success = 0
    errors = []

    for index, filename in enumerate(pdf_files):
        current_num = index + 1
        progress = current_num / total * 100
        pdf_path = os.path.join(source_dir, filename)
        
        # 进度显示
        status_line = f"[{current_num}/{total} {progress:.1f}%] 正在处理 {filename}"
        print(status_line.ljust(80), end='\r')  # 覆盖式进度显示

        try:
            with fitz.open(pdf_path) as doc:
                page = doc[0]
                matrix = fitz.Matrix(zoom, zoom)
                pix = page.get_pixmap(matrix=matrix)
                
                png_name = os.path.splitext(filename)[0] + '.png'
                png_path = os.path.join(target_dir, png_name)
                pix.save(png_path)
                
            success += 1
            print(f"✅ [{current_num}/{total}] 转换成功: {filename}".ljust(80))
            
        except Exception as e:
            error_msg = f"❌ [{current_num}/{total}] 转换失败: {filename} - {str(e)}"
            print(error_msg.ljust(80))
            errors.append(error_msg)

    # 最终统计
    print("\n\n转换完成:")
    print(f"✓ 成功: {success} 个")
    print(f"✗ 失败: {len(errors)} 个")
    
    if errors:
        print("\n错误详情:")
        for error in errors:
            print(f"  {error}")

# 使用示例
if __name__ == "__main__":
    pdf_first_page_to_png(
        source_dir="./pdfs",
        target_dir="./imgs",
        zoom=3
    )